/** @format */

import { ref } from 'vue'

export function useCache<T>(key: string, ttl: number = 1000 * 60 * 5) {
  const getItem = (): T | null => {
    const item = uni.getStorageSync(key)
    if (!item) return null

    const { value, timestamp } = JSON.parse(item)
    if (ttl > 0 && Date.now() - timestamp > ttl) {
      uni.removeStorageSync(key)
      return null
    }
    return value
  }

  const setItem = (value: T) => {
    const item = {
      value,
      timestamp: Date.now(),
    }

    uni.setStorageSync(key, JSON.stringify(item))
  }

  return { getItem, setItem }
}
